package com.springcloud.feigndemoserver1000.servie;

import com.springcloud.common.dto.PageDTO;
import com.springcloud.common.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class UserService {
    private static List<UserDTO> userDTOS = new ArrayList<>();
    static {
        userDTOS.add(new UserDTO(1,"张1",10,"张1,年龄是10岁"));
        userDTOS.add(new UserDTO(2,"张2",30,"张2,年龄是30岁"));
        userDTOS.add(new UserDTO(3,"张3",19,"张3,年龄是19岁"));
        userDTOS.add(new UserDTO(4,"张4",20,"张4,年龄是20岁"));
        userDTOS.add(new UserDTO(5,"张5",19,"张5,年龄是19岁"));
        userDTOS.add(new UserDTO(6,"张6",40,"张6,年龄是40岁"));
        userDTOS.add(new UserDTO(7,"张7",19,"张7,年龄是19岁"));
        userDTOS.add(new UserDTO(8,"张8",20,"张8,年龄是20岁"));
        userDTOS.add(new UserDTO(9,"张9",10,"张9,年龄是10岁"));
        userDTOS.add(new UserDTO(10,"张10",22,"张10,年龄是22岁"));
        userDTOS.add(new UserDTO(11,"张11",19,"张11,年龄是19岁"));
    }

    /*
     * @Author ZhangBin
     * @Date 2020/6/30 11:29
     * @Description: 根据id获取用户信息
     *
     **/
    public UserDTO getUserById(Integer id){
        if(id == null){
            RuntimeException e = new RuntimeException("id不能为空");
            log.error("id不能为空",e);
            throw e;
        }
        Optional<UserDTO> first = Optional.ofNullable(userDTOS)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(x -> id.equals(x.getId()))
                .findFirst();
        if(first.isPresent()){
            return first.get();
        }
        return null;
    }

    public PageDTO<UserDTO> getUserPage(PageDTO pageDTO) {
        int pageNum = pageDTO.getPageNum()==null||pageDTO.getPageNum()<0?0:pageDTO.getPageNum();
        int pageSize = pageDTO.getPageSize()==null||pageDTO.getPageSize()<=0?3:pageDTO.getPageSize();

        int startIndex = ((pageNum-1)*pageSize)<0?0:(pageNum-1)*pageSize;
        if(startIndex>userDTOS.size()){
            startIndex = (userDTOS.size() - pageSize)<0?0:userDTOS.size() - pageSize;
        }
        int endIndex = startIndex + pageSize;
        if(endIndex>userDTOS.size()){
            endIndex = userDTOS.size();
        }
        List<UserDTO> userDTOS = UserService.userDTOS.subList(startIndex, endIndex);
        PageDTO pages = new PageDTO();
        pages.setTotalSize(userDTOS.size());
        pages.setPageNum(pageNum);
        pages.setPageSize(pageSize);
        pages.setPageContent(userDTOS);
        return pages;
    }

    public static void main(String[] args) {
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(2);
        pageDTO.setPageSize(null);
        PageDTO<UserDTO> userPage = new UserService().getUserPage(pageDTO);
        System.out.println(userPage.getPageContent());
    }
}
